<template>
  <div class="register-container">
    <el-card class="box-card bg-white shadow-lg rounded-lg">
      <template #header>
        <div class="flex justify-center">
          <h3 class="text-2xl font-bold text-orange-500">用户注册</h3>
        </div>
      </template>
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          class="demo-ruleForm"
      >
        <el-form-item label="账号名" prop="account">
          <el-input v-model="form.account" placeholder="请输入账号名" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
              v-model="form.password"
              type="password"
              placeholder="请输入密码"
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
              v-model="form.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
          />
        </el-form-item>

        <el-form-item label="昵称">
          <el-input v-model="form.nickname" placeholder="请输入昵称" />
        </el-form-item>

        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="form.realName" placeholder="请输入真实姓名" />
        </el-form-item>

        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号码" />
        </el-form-item>

        <el-form-item label="邮箱地址" prop="email">
          <el-row :gutter="10">
            <el-col :span="18">
              <el-input v-model="form.email" placeholder="请输入邮箱地址" />
            </el-col>
            <el-col :span="6">
              <el-button
                  :disabled="sending || countdown > 0"
                  @click="sendVerifyCode"
                  type="primary"
                  size="small"
                  :class="{ 'bg-orange-500 hover:bg-orange-600': !sending && countdown <= 0 }"
              >
                {{ countdown > 0 ? `${countdown}s后重新发送` : '发送验证码' }}
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="邮箱验证码" prop="verifyCode">
          <el-input v-model="form.verifyCode" placeholder="请输入邮箱验证码" />
        </el-form-item>

        <el-form-item class="flex justify-center gap-4 pt-4">
          <el-button
              @click="resetForm(formRef)"
              class="px-6 py-2 border border-gray-300 rounded-lg hover:bg-gray-100 transition-colors"
          >
            取消
          </el-button>
          <el-button
              type="primary"
              @click="submitForm(formRef)"
              class="px-6 py-2 bg-orange-500 hover:bg-orange-600 text-white rounded-lg transition-colors"
          >
            提交
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onUnmounted } from 'vue'
import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";
import { userStore } from '@/store/index.js'
const userItemStore = userStore();

const formRef = ref(null)

const form = reactive({
  account: '',
  password: '',
  confirmPassword: '',
  nickname: '',
  realName: '',
  mobile: '',
  email: '',
  verifyCode: '',
  isCodeSent: false
})

const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请确认密码'))
  } else if (value !== form.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}
// 邮箱验证正则表达式
const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

const rules = reactive({
  account: [
    { required: true, message: '请输入账号名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入邮箱地址'));
        } else if (!emailPattern.test(value)) {
          callback(new Error('请输入正确的邮箱地址'));
        } else {
          callback();
        }
      },
      trigger: ['blur', 'change']  }
  ],
  verifyCode: [
    {
      required: true,
      message: '请输入邮箱验证码',
      trigger: 'blur'
    },
    {
      min: 6,
      max: 6,
      message: '验证码为6位数字',
      trigger: 'blur',
      validator: (rule, value) => /^\d{6}$/.test(value)
    }
  ]
})

const sending = ref(false)
const countdown = ref(0)
let timer = null


// 自定义邮箱验证函数
const validateEmail = (callback) => {
  if (!emailPattern.test(form.email)) {
    callback(false);
    return;
  }
  callback(true);
}

const sendVerifyCode = () => {
  if (sending.value || countdown.value > 0) return

  // 使用自定义验证函数
  validateEmail((valid) => {
    if (!valid) {
      ElMessage.error('请输入正确的邮箱地址');
      return;
    }

    sending.value = true;

    // 邮箱地址格式正确才发送邮件
    axios.get(`/user/sendEmail?address=${form.email}`)
        .then((resp) => {
          if (resp.status === 200) {
            ElMessage.success('验证码已发送到邮箱地址！');
            form.isCodeSent = true;

            // 启动倒计时
            countdown.value = 60;
            timer = setInterval(() => {
              countdown.value--;
              if (countdown.value <= 0) {
                clearInterval(timer);
                timer = null;
                sending.value = false;
              }
            }, 5000);
          } else {
            throw new Error('发送失败，状态码：' + resp.status);
          }
        })
        .catch((error) => {
          console.error('发送验证码失败', error);
          ElMessage.error(error.response?.data?.message || '发送失败，请稍后再试');
          sending.value = false;
          form.isCodeSent = false;
        })
        .finally(() => {
          sending.value = false;
        });
  })
}

const submitForm = (formEl) => {
  if (!formEl) return

  if (!form.isCodeSent) {
    ElMessage.warning('请先发送邮箱验证码');
    return;
  }

  formEl.validate((valid) => {
    if (valid) {
      // 将注册信息以post方式提交给服务器
      axios.post(`/user/register`, form)
          .then(res => {
            // 提示注册成功
            ElMessage({
              message: '用户注册成功',
              type: 'success'
            });

            // 更新用户登录的信息
            userItemStore.updateUser(res.data);
            userItemStore.updateLoginStatus(true);

            // 本地存储
            localStorage.setItem('user', JSON.stringify(res.data));
            localStorage.setItem("token", res.headers['authorization']);

            // 跳转到热销榜
            router.push("/getBookType?id=0");
          })
          .catch(err => {
            console.error('注册失败', err);
            ElMessage.error(err.response.data );
          });
    } else {
      console.log('表单验证失败，请检查输入内容');
      return false;
    }
  })
}

const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();

  if (timer) {
    clearInterval(timer);
    timer = null;
  }

  countdown.value = 0;
  sending.value = false;
  form.isCodeSent = false;
}

onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
})
</script>

<style scoped>
.register-container {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}

.box-card {
  margin-top: 20px;
}

/* 自定义ElementPlus表单样式 */
.el-form-item__label {
  color: #333 !important;
}

.el-input__inner:focus {
  border-color: #f97316 !important;
  box-shadow: 0 0 0 2px rgba(249, 115, 22, 0.2) !important;
}

.el-button--primary {
  background-color: #f97316 !important;
  border-color: #f97316 !important;
}

.el-button--primary:hover {
  background-color: #ea580c !important;
  border-color: #ea580c !important;
}

.el-form-item__error {
  color: #ef4444 !important;
}
</style>